package com.ruoyi.ftrl.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.config.MessageEventListener;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.ftrl.common.ByteUtil;
import com.ruoyi.ftrl.domain.ControlValve;
import com.ruoyi.ftrl.domain.RoomInfo;
import com.ruoyi.ftrl.domain.TemperatureControl;
import com.ruoyi.ftrl.mapper.ControlValveMapper;
import com.ruoyi.ftrl.mapper.RoomInfoMapper;
import com.ruoyi.ftrl.mapper.TemperatureControlMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;


@Service
public class RedisMessageHandler implements MessageEventListener {

    @Autowired
    private ControlValveMapper controlValveMapper;
    @Autowired
    //Redis工具类
    RedisCache redisCache;
    @Autowired
    TemperatureControlMapper temperatureControlMapper;
    @Autowired
    private RoomInfoMapper roomInfoMapper;

    private final ObjectMapper objectMapper;
    @Autowired
    public RedisMessageHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /**
     * 监听器（阀门数据监听）
     * @param message
     */
    @Override
    public void onMessage(String message) {

        System.out.println("Received message(监听到频道号------student------的消息为): " + message);
//        //todo 将得到的消息进行解码
        //十六进制转换十进制
        //Integer.parseInt("",16);
        String messagetht="eb90eb90eb904801a30000000000000000000000ffffffff026400000000000002000000002b00005245470000000064000000004f0000000000000000000000000000007c061a1004000000000074";
            ControlValve controlValve=new ControlValve();

        //帧头
        String head = message.substring(0, 12);
        controlValve.setHeader(head);
        if (!head.equals("eb90eb90eb90")){
            //   throw new ServerException("错误");
            System.out.println("\"帧头::\" = " + "帧头错误");
        }
        //长度 72 144
        String len = message.substring(12, 14);
        Integer length = Integer.parseInt(len, 16);
        controlValve.setLen(length.toString());

        //功能码
        String key = message.substring(14, 16);
        if (key.equals("01")){
            System.out.println(" = " + "功能码正常");
        }else if (key.equals("41")){
            System.out.println(" = " + "错误码0x41");
        } else if (key.equals("18")) {
            System.out.println("\"\" = " + "设置阀通断正常 0x18");
        } else if (key.equals("58")) {
            System.out.println("\"\" = " + "设置阀通断错误,错误码0x58");
        } else if (key.equals("0a")) {
            System.out.println("\"\" = " + "校时正常");
        }
        //设备ID
        String sid =  message.substring(18, 20)+message.substring(16, 18);
        String s = String.valueOf(Integer.parseInt(sid, 16));
        //String s2 = String.valueOf(Integer.parseInt(sid2, 16));
        controlValve.setEid(s);

        //时间 年 月 日 时 分 秒
//        String substring = message.substring(20, 22)+message.substring(22,24)+message.substring(24,26)+message.substring(26,28)+message.substring(28,30)+message.substring(30,32);
//        // 解析字符串为 LocalDateTime 对象
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
//        LocalDateTime dateTime = LocalDateTime.parse(substring, formatter);
//        // 格式化为指定的时间字符串
//        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        substring = dateTime.format(outputFormatter);
//        System.out.println("实际时间为："+substring);
//        Instant instant = dateTime.atZone(ZoneId.systemDefault()).toInstant();
//        // 转换为 Date
//        Date date = Date.from(instant);
        controlValve.setTime(new Date());

        //通断状态  目前显示全是0
        controlValve.setColectsta(message.substring(32,40));

        //通讯状态  目前显示全F
        controlValve.setTransprotsta(message.substring(40,48));

        //计量点  (子设备id 设计模式不明) 1字节hex
        String substring = message.substring(48, 50);
        int i = Integer.parseInt(substring, 16);
        substring=String.valueOf(i);
        controlValve.setMeternum(substring);
        String string =substring;

        //表类型  (目前只发现100) 表类型 1字节hex
        controlValve.setType(String.valueOf(Integer.parseInt(message.substring(50,52), 16)));
        String type = String.valueOf(Integer.parseInt(message.substring(50, 52), 16));

        //标号 (未知)
        String bcd = message.substring(64, 66)+message.substring(62,64)+message.substring(60,62)+message.substring(58,60)+message.substring(56,58)+message.substring(54,56)+message.substring(52,54);
        byte[] bytes = ByteUtil.bcdStringToBytes(bcd);
        controlValve.setValveid(ByteUtil.bytesToHex(bytes));



        //室内温度
        int anInt = Integer.parseInt(message.substring(68, 70) + message.substring(66, 68), 16);
        BigDecimal bigDecimal=new BigDecimal(anInt);
        BigDecimal divide = bigDecimal.divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
        controlValve.setIndoortemp(divide.toString());

        //室内设置温度
        int anInt1 = Integer.parseInt(message.substring(72, 74) + message.substring(70, 72), 16);
        BigDecimal bigDecimal1=new BigDecimal(anInt1);
        BigDecimal divide1 = bigDecimal1.divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
        controlValve.setIndoorsettemp(divide1.toString());

        //空

        //最近两小时平均温度

        int anInt2 = Integer.parseInt(message.substring(78, 80) + message.substring(76, 78), 16);
        BigDecimal bigDecimal2=new BigDecimal(anInt2);
        BigDecimal divide2 = bigDecimal2.divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
        controlValve.setAgvindoortemp(divide2.toString());

        // controlValve.setAgvindoortemp(String.valueOf(Integer.parseInt(message.substring(76,80), 16)));

        //空 六位
        //controlValve.setnc2(String.valueOf(Integer.parseInt(message.substring(76,80), 16)));

        //进水温度
        int anInt3 = Integer.parseInt(message.substring(88, 90) + message.substring(86, 88), 16);
        BigDecimal bigDecimal3=new BigDecimal(anInt3);
        BigDecimal divide3 = bigDecimal3.divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
        controlValve.setIntemp(divide3.toString());

//        controlValve.setIntemp(String.valueOf(Integer.parseInt(message.substring(86,90), 16)));
        //回水温度
        int anInt4 = Integer.parseInt(message.substring(92, 94) + message.substring(90, 92), 16);
        BigDecimal bigDecimal4=new BigDecimal(anInt4);
        BigDecimal divide4= bigDecimal4.divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
        controlValve.setOuttemp(divide4.toString());

        //  controlValve.setOuttemp(String.valueOf(Integer.parseInt(message.substring(90,94), 16)));

        //阀门开合角度
        controlValve.setValveangle(String.valueOf(Integer.parseInt(message.substring(94,96), 16)));

        //累计工作时间 分钟
        String time =  message.substring(102, 104)+message.substring(100, 102)+ message.substring(98, 100)+message.substring(96, 98);
        String a = String.valueOf(Integer.parseInt(time, 16));
        controlValve.setWorktime(a);
        //空3
        //2
        //累计阀门开启时间
        String time1 =  message.substring(112, 114)+message.substring(110, 112)+ message.substring(108, 110)+message.substring(106, 108);
        String a1 = String.valueOf(Integer.parseInt(time1, 16));
        controlValve.setOpentime(a1);
        //controlValve.setOpentime(String.valueOf(Integer.parseInt(message.substring(106,114), 16)));

        //空  22位
        //实时时间 bcd解码
        String bcd1 = message.substring(148, 150)+message.substring(146,148)+message.substring(144,146)+message.substring(142,144)+message.substring(140,142)+message.substring(138,140)+message.substring(136,138);
        byte[] bytes1 = ByteUtil.bcdStringToBytes(bcd1);
        controlValve.setRealtime(ByteUtil.bytesToHex(bytes1));

        //controlValve.setRealtime(message.substring(136,150));
        //ST状态字 6
        controlValve.setStsta(message.substring(150,156));
        //校检和
        controlValve.setCrc(message.substring(156,158));



        // todo 根据集中器ID和计量点ID来查询该温控阀设备的基本安装信息，进行房间基础，信息查询并赋值
        System.out.println("sid--------"+s+"string--------"+string);
        TemperatureControl temperatureControl=temperatureControlMapper.selectTemperatureControlByIds(s,string);
        RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(temperatureControl.getRoomNo());
        if (roomInfo!=null&&!type.equals("2")){
            //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
            //计量点ID
            controlValve.setMeternum(temperatureControl.getNodeId());
            //集中器ID
            controlValve.setNodeId(temperatureControl.getFocusId());
            controlValve.setRoomNo(temperatureControl.getRoomNo());
            controlValve.setVillageName(temperatureControl.getCommunityName());
            controlValve.setBuildingName(temperatureControl.getBuildingName());
            controlValve.setUnitName(temperatureControl.getUnitName());
            controlValve.setRoomName(controlValve.getBuildingName()+"-"+controlValve.getUnitName()+"-"+temperatureControl.getRoomAme());
            controlValve.setUserCode(roomInfo.getPersonName());
            controlValve.setTelephone(roomInfo.getPhone());
            controlValve.setRoomType("其他");
            controlValve.setLocation(temperatureControl.getInstall());
//            controlValve.setUploadtime(new Date());
            controlValve.setManufactor("1");
            controlValve.setCreateTime(new Date());
//            controlValve.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//            controlValve.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//            controlValve.setRoomState("正常");
            controlValve.setState("0");
            controlValve.setHistory("1");
            //todo 将该表的表类型进行赋值
            controlValve.setType(temperatureControl.getDeviceType());
        }else {
            //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
            //计量点ID
            controlValve.setMeternum(temperatureControl.getNodeId());
            //集中器ID
            controlValve.setNodeId(temperatureControl.getFocusId());
            controlValve.setRoomNo(temperatureControl.getRoomNo());
            controlValve.setVillageName(temperatureControl.getCommunityName());
            controlValve.setBuildingName(temperatureControl.getBuildingName());
            controlValve.setUnitName(temperatureControl.getUnitName());
            controlValve.setRoomName(controlValve.getBuildingName()+"-"+controlValve.getUnitName()+"-"+temperatureControl.getRoomAme());
            controlValve.setRoomType("其他");
            controlValve.setLocation(temperatureControl.getInstall());
//            controlValve.setUploadtime(new Date());
            controlValve.setManufactor("1");
            controlValve.setCreateTime(new Date());
//            controlValve.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//            controlValve.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//            controlValve.setRoomState("正常");
            controlValve.setState("0");
            controlValve.setHistory("1");
            //todo 将该表的表类型进行赋值
            controlValve.setType(temperatureControl.getDeviceType());

        }
        //将最新数据存储前，将表中现有数据更改为历史数据
       ControlValve controlValve1= controlValveMapper.selectControlValveByRoomNoType(controlValve.getRoomNo(),controlValve.getType());
        if (controlValve1!=null){
            //将此数据更改为历史数据
            controlValveMapper.updateControlValveHistory(controlValve1.getId());
        }
        // 将数据存入数据库
        controlValveMapper.insertControlValve(controlValve);
    }

    public static void main(String[] args) {
        String message="eb90eb90eb904801a30000000000000000000000ffffffff026400000000000002000000002b00005245470000000064000000004f0000000000000000000000000000007c061a1004000000000074";
        ControlValve controlValve=new ControlValve();
//        //帧头
//        String head = message.substring(0, 12);
//        controlValve.setHeader(head);
//        if (!head.equals("eb90eb90eb90")){
////            throw new ServiceException("帧头错误");
//            System.out.println("\"帧头::\" = " + "帧头错误");
//        }
//        //长度 72 144
//        String len = message.substring(12, 14);
//        Integer length = Integer.parseInt(len, 16);
//        controlValve.setLen(length.toString());
//
//        //功能码
//        String key = message.substring(14, 16);
//        if (key.equals("01")){
//             System.out.println(" = " + "功能码正常");
//        }else if (key.equals("41")){
//            System.out.println(" = " + "错误码0x41");
//        } else if (key.equals("18")) {
//            System.out.println("\"\" = " + "设置阀通断正常 0x18");
//        } else if (key.equals("58")) {
//            System.out.println("\"\" = " + "设置阀通断错误,错误码0x58");
//        } else if (key.equals("0a")) {
//            System.out.println("\"\" = " + "校时正常");
//        }
//        //设备ID
//        String sid = message.substring(18, 20)+message.substring(16,18);
//        controlValve.setEid(String.valueOf(Integer.parseInt(sid, 16)) );
//        String string = String.valueOf(Integer.parseInt(sid, 16));
//        System.out.println("设备ID为："+string);
//
//        //时间
//        String substring = message.substring(30, 32)+message.substring(28,30)+message.substring(26,28)+message.substring(24,26)+message.substring(22,24)+message.substring(20,22);
//        System.out.println("字符串时间为："+substring);
////        // 解析字符串为 LocalDateTime 对象
////        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
////        LocalDateTime dateTime = LocalDateTime.parse(substring, formatter);
////        // 格式化为指定的时间字符串
////        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
////        substring = dateTime.format(outputFormatter);
////        System.out.println("实际时间为："+substring);
////        Instant instant = dateTime.atZone(ZoneId.systemDefault()).toInstant();
////        // 转换为 Date
////        Date date = Date.from(instant);
//        controlValve.setTime(new Date());
//
//        //通断状态
//        controlValve.setColectsta( message.substring(32,40));
//
//        //通讯状态
//        controlValve.setTransprotsta(message.substring(40,48));
//
//        //计量点  (子设备id 设计模式不明)
//        controlValve.setMeternum(String.valueOf(Integer.parseInt(message.substring(48,50), 16)));
//
//
//        //表类型  (目前只发现100)
//        controlValve.setType(String.valueOf(Integer.parseInt(message.substring(50,52), 16)));
//
//        //标号 (未知)
//        controlValve.setValveid(message.substring(52,66));
//
//        //室内温度
//        controlValve.setIndoortemp(String.valueOf(Integer.parseInt(message.substring(66,70), 16)));
//
//        //室内设置温度
//        controlValve.setIndoorsettemp(String.valueOf(Integer.parseInt(message.substring(70,74), 16)));
//        //空
//
//        //最近两小时平均温度
//        controlValve.setAgvindoortemp(String.valueOf(Integer.parseInt(message.substring(76,80), 16)));
//
//        //空 六位
//        //controlValve.setnc2(String.valueOf(Integer.parseInt(message.substring(76,80), 16)));
//
//        //进水温度
//        controlValve.setIntemp(String.valueOf(Integer.parseInt(message.substring(86,90), 16)));
//        //回水温度
//        controlValve.setOuttemp(String.valueOf(Integer.parseInt(message.substring(90,94), 16)));
//
//        //阀门开合角度
//        controlValve.setValveangle(String.valueOf(Integer.parseInt(message.substring(94,96), 16)));
//
//        //累计工作时间
//        controlValve.setWorktime(String.valueOf(Integer.parseInt(message.substring(96,104), 16)));
//        //空3
//        //2
//        //累计阀门开启时间
//        controlValve.setOpentime(String.valueOf(Integer.parseInt(message.substring(106,114), 16)));
//
//        //空  22位
//        //实时时间 bcd解码
//        controlValve.setRealtime(message.substring(136,150));
//        //ST状态字 6
//        controlValve.setStsta(message.substring(150,156));
//        //校检位
//        controlValve.setCrc(message.substring(156,158));

        //帧头
        String head = message.substring(0, 12);
        controlValve.setHeader(head);
        if (!head.equals("eb90eb90eb90")){
            //   throw new ServerException("错误");
            System.out.println("\"帧头::\" = " + "帧头错误");
        }
        //长度 72 144
        String len = message.substring(12, 14);
        Integer length = Integer.parseInt(len, 16);
        controlValve.setLen(length.toString());

        //功能码
        String key = message.substring(14, 16);
        if (key.equals("01")){
            System.out.println(" = " + "功能码正常");
        }else if (key.equals("41")){
            System.out.println(" = " + "错误码0x41");
        } else if (key.equals("18")) {
            System.out.println("\"\" = " + "设置阀通断正常 0x18");
        } else if (key.equals("58")) {
            System.out.println("\"\" = " + "设置阀通断错误,错误码0x58");
        } else if (key.equals("0a")) {
            System.out.println("\"\" = " + "校时正常");
        }
        //设备ID
        String sid =  message.substring(18, 20)+message.substring(16, 18);
        String s = String.valueOf(Integer.parseInt(sid, 16));
        //String s2 = String.valueOf(Integer.parseInt(sid2, 16));
        controlValve.setEid(s);

        //时间 年 月 日 时 分 秒
        String substring = message.substring(20, 22)+message.substring(22,24)+message.substring(24,26)+message.substring(26,28)+message.substring(28,30)+message.substring(30,32);
//        controlValve.setTime(substring);

        //通断状态  目前显示全是0
        controlValve.setColectsta(message.substring(32,40));

        //通讯状态  目前显示全F
        controlValve.setTransprotsta(message.substring(40,48));

        //计量点  (子设备id 设计模式不明) 1字节hex
        controlValve.setMeternum(String.valueOf(Integer.parseInt(message.substring(48,50), 16)));

        //表类型  (目前只发现100) 表类型 1字节hex
        controlValve.setType(String.valueOf(Integer.parseInt(message.substring(50,52), 16)));

        //标号 (未知)
        String bcd = message.substring(64, 66)+message.substring(62,64)+message.substring(60,62)+message.substring(58,60)+message.substring(56,58)+message.substring(54,56)+message.substring(52,54);
        byte[] bytes = ByteUtil.bcdStringToBytes(bcd);
        controlValve.setValveid(ByteUtil.bytesToHex(bytes));



        //室内温度
        int anInt = Integer.parseInt(message.substring(68, 70) + message.substring(66, 68), 16);
        BigDecimal bigDecimal=new BigDecimal(anInt);
        BigDecimal divide = bigDecimal.divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
        controlValve.setIndoortemp(divide.toString());

        //室内设置温度
        int anInt1 = Integer.parseInt(message.substring(72, 74) + message.substring(70, 72), 16);
        BigDecimal bigDecimal1=new BigDecimal(anInt1);
        BigDecimal divide1 = bigDecimal1.divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
        controlValve.setIndoorsettemp(divide1.toString());

        //空

        //最近两小时平均温度

        int anInt2 = Integer.parseInt(message.substring(78, 80) + message.substring(76, 78), 16);
        BigDecimal bigDecimal2=new BigDecimal(anInt2);
        BigDecimal divide2 = bigDecimal2.divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
        controlValve.setAgvindoortemp(divide2.toString());

        // controlValve.setAgvindoortemp(String.valueOf(Integer.parseInt(message.substring(76,80), 16)));

        //空 六位
        //controlValve.setnc2(String.valueOf(Integer.parseInt(message.substring(76,80), 16)));

        //进水温度
        int anInt3 = Integer.parseInt(message.substring(88, 90) + message.substring(86, 88), 16);
        BigDecimal bigDecimal3=new BigDecimal(anInt3);
        BigDecimal divide3 = bigDecimal3.divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
        controlValve.setIntemp(divide3.toString());

//        controlValve.setIntemp(String.valueOf(Integer.parseInt(message.substring(86,90), 16)));
        //回水温度
        int anInt4 = Integer.parseInt(message.substring(92, 94) + message.substring(90, 92), 16);
        BigDecimal bigDecimal4=new BigDecimal(anInt4);
        BigDecimal divide4= bigDecimal4.divide(new BigDecimal(100),2,BigDecimal.ROUND_DOWN);
        controlValve.setOuttemp(divide4.toString());

        //  controlValve.setOuttemp(String.valueOf(Integer.parseInt(message.substring(90,94), 16)));

        //阀门开合角度
        controlValve.setValveangle(String.valueOf(Integer.parseInt(message.substring(94,96), 16)));

        //累计工作时间 分钟
        String time =  message.substring(102, 104)+message.substring(100, 102)+ message.substring(98, 100)+message.substring(96, 98);
        String a = String.valueOf(Integer.parseInt(time, 16));
        controlValve.setWorktime(a);
        //空3
        //2
        //累计阀门开启时间
        String time1 =  message.substring(112, 114)+message.substring(110, 112)+ message.substring(108, 110)+message.substring(106, 108);
        String a1 = String.valueOf(Integer.parseInt(time1, 16));
        controlValve.setOpentime(a1);
        //controlValve.setOpentime(String.valueOf(Integer.parseInt(message.substring(106,114), 16)));

        //空  22位
        //实时时间 bcd解码
        String bcd1 = message.substring(148, 150)+message.substring(146,148)+message.substring(144,146)+message.substring(142,144)+message.substring(140,142)+message.substring(138,140)+message.substring(136,138);
        byte[] bytes1 = ByteUtil.bcdStringToBytes(bcd1);
        controlValve.setRealtime(ByteUtil.bytesToHex(bytes1));

        //controlValve.setRealtime(message.substring(136,150));
        //ST状态字 6
        controlValve.setStsta(message.substring(150,156));
        //校检和
        controlValve.setCrc(message.substring(156,158));



    }

}